#-*-coding: utf-8-*-

# Version: 0.1
# Author: Don Li <iedon@126.com>
# License: Copyright(c) 2017 Don.Li
# Summary:

from log              import log
from models.task      import Task
from services.worker  import process
from services.prgpool import Pool

class Dispatcher(object):
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Dispatcher, cls).__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self):
        self.__pool = Pool()
        self.__pool.start()

    async def calc(self, request):
        task = Task(request)

        task.result = await self.__pool.apply(process, request, timeout = 1)
        log.info('[ Dispatcher.calc ] params: {0}, res: {1}.'.format(request, task.result))

        return task

    def stop(self, _):
        self.__pool.stop()
        log.info('[ Dispatcher ]: stopped.')

dispatcher = Dispatcher()
